#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "utils.h"
#include "httpmgr.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QtConcurrent>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->hide();

    QIcon icon(":/images/dog_svg.svg");
    this->setWindowIcon(icon);
    this->setWindowTitle(" ");

    _login_dlg = new LoginDialog();
    //登录验证成功，通知准备开始聊天服务逻辑
    connect(_login_dlg,&LoginDialog::sig_login_finish,this,&MainWindow::fromLoginDialog_slot_login_login_finish);
    _login_dlg->show();


//    QJsonObject json_obj;
//    json_obj["Id"] = 1;
//    json_obj["Identity"] = "identity";
//    fromLoginDialog_slot_login_login_finish(json_obj);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::fromLoginDialog_slot_login_login_finish(QJsonObject userData)
{
    //销毁登录界面和与其相关的信号与槽
    _login_dlg->hide();
    disconnect(_login_dlg,&LoginDialog::sig_login_finish,this,
               &MainWindow::fromLoginDialog_slot_login_login_finish);
    _login_dlg->deleteLater();

    //聊天界面逻辑
    int id = userData["Id"].toInt();
    QString name = userData["Name"].toString();
    QString email = userData["Email"].toString();
    QString identity = userData["Identity"].toString();
    QString avatar = userData["Avatar"].toString();
    QJsonArray friendList = userData["FriendList"].toArray();

    //初始化用户储存路径
    AVATAR_PATH = AVATAR_PATH  + QString::number(id) +QDir::separator()+ "avatar"+QDir::separator();
    IMAGE_MSG_PATH = IMAGE_MSG_PATH + QString::number(id) +QDir::separator()+ "msg_image"+QDir::separator();
    USER_PATH = USER_PATH + QString::number(id) + QDir::separator();
    NEEDLoadAvatarNums = friendList.size()+1;//记录需要加载的头像数量
    qDebug()<<NEEDLoadAvatarNums;//NEEDLoadAvatarNums == -1不做处理 0通知主线程显示聊天界面 大于0则继续迭代

    initDatabase();
    saveFriendInfo(friendList);//保存好友信息
    //开启一个线程处理服务器发送的资源
    work_background_thread = new QThread;
    work_background = new BackgroundThread(id);
    work_background->moveToThread(work_background_thread);
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_thread_mod_finish,
            work_background,&BackgroundThread::slot_thread_mod_finish);
    connect(work_background,&BackgroundThread::sig_iamgeMsg,this,&MainWindow::requestImageMsg);
    connect(work_background,&BackgroundThread::sig_finishAvatrLoad,this,&MainWindow::showChatUi);
    work_background_thread->start();
    _chat_dlg = new ChatDialog(id,name,email,identity,avatar);
    connect(work_background,&BackgroundThread::sig_lastMsg,_chat_dlg,&ChatDialog::slot_loadChatItem);
    _chat_dlg->init_user(friendList);//请求头像数据


    //新线程处理消息的发送与接收
    chat_service_thread = new QThread;
    chat_service = new ChatService(QString::number(id),identity);
    chat_service->moveToThread(chat_service_thread);
    connect(chat_service_thread,&QThread::started,chat_service,
            &ChatService::slot_initWebsocket);
    connect(_chat_dlg,&ChatDialog::sendTextMsg,chat_service,
            &ChatService::slot_sendTextMsg);//发送文本消息
    connect(_chat_dlg,&ChatDialog::sendImageMsg,chat_service,
            &ChatService::slot_sendImageMsg);//发送图片消息
    connect(chat_service,&ChatService::sig_TextMessageReceived,_chat_dlg,&ChatDialog::slot_recvMsg);
    chat_service_thread->start();


}

void MainWindow::requestImageMsg(QString imageName)
{
    //获取好友头像图片
    QJsonObject imageMsgJson;
    imageMsgJson["filename"] = imageName;
    imageMsgJson["Type"] = 2;//1头像 2聊天消息
    HttpMgr::GetInstance()->GetHttpReq(QUrl(gate_url_prefix+"/toGetImage"),
                                       imageMsgJson, ReqId::ID_CHAT_GETIAMGEMsg,Modules::thread);
}

void MainWindow::showChatUi()
{
    _chat_dlg->show_imageInfo();//加载图片到界面
    _chat_dlg->show();
    NEEDLoadAvatarNums = -1;
}

void MainWindow::initDatabase()
{
    const QString connectionName = "init";
    QSqlDatabase db;

    // 首先尝试获取已存在的连接
    if (QSqlDatabase::contains(connectionName)) {
        db = QSqlDatabase::database(connectionName);
        if (!db.open()) {
            qDebug() << "无法打开已存在的数据库连接initDatabase:" << db.lastError().text();
                return;
        }
    } else {
        // 连接不存在，添加新连接
        db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        QString databasePath = USER_PATH + "user.db";
        QString relativeFilePath = QDir::currentPath() + QDir::separator() + databasePath;
        QFileInfo fileInfo(relativeFilePath);
        QDir dir = fileInfo.absoluteDir();
        if (!dir.exists())
        {
                // 如果目录不存在，则创建目录，此处使用mkpath可以创建多级目录（包含中间缺失的目录）
                if (dir.mkpath("."))
                {
                    qDebug() << "目录创建成功initDatabase" << relativeFilePath;
                }
                else
                {
                    qDebug() << "创建目录时出错initDatabase"<< relativeFilePath;
                    return;
                }
        }
        db.setDatabaseName(databasePath);
        if (!db.open()) {
            qDebug() << "无法打开新的数据库连接initDatabase:" << db.lastError().text();
                return;
        }
    }


    // 创建一个 SQL 查询对象
    QSqlQuery query(db);

    // 创建 messages 表的 SQL 语句，设置 msgId 和 score 为复合主键
    QString createMessagesTableQuery = "CREATE TABLE IF NOT EXISTS messages ("
                                       "msgId TEXT, "
                                       "TargetId INTEGER, "
                                       "Type INTEGER, "
                                       "Media INTEGER, "
                                       "Content TEXT, "
                                       "CreateTime REAL, "
                                       "ReadTime REAL, "
                                       "score REAL, "
                                       "PRIMARY KEY (msgId, score)"
                                       ")";

    // 执行创建 messages 表的 SQL 语句
    if (query.exec(createMessagesTableQuery)) {
        if (query.numRowsAffected() == 0) {
            //qDebug() << "表 'messages' 已经存在，无需创建。";
        } else {
            //qDebug() << "表 'messages' 创建成功。";
        }
    } else {
        qDebug() << "创建表 'messages' 失败initDatabase:" << query.lastError().text();
                                                          db.close();
        return ;
    }

    // 创建 contacts 表的 SQL 语句
    QString createContactsTableQuery = "CREATE TABLE IF NOT EXISTS contacts ("
                                       "friend_id INTEGER PRIMARY KEY, "
                                       "name TEXT, "
                                       "email TEXT, "
                                       "avatar TEXT)";


    // 执行创建 contacts 表的 SQL 语句
    if (query.exec(createContactsTableQuery)) {
        if (query.numRowsAffected() == 0) {
            //qDebug() << "表 'contacts' 已经存在，无需创建。";
        } else {
            //qDebug() << "表 'contacts' 创建成功。";
        }
    } else {
        qDebug() << "创建表 'contacts' 失败initDatabase:" << query.lastError().text();
    }

    // 关闭数据库
    db.close();
}

void MainWindow::saveFriendInfo(QJsonArray friendList)
{
    if(friendList.isEmpty())
        return;
    const QString connectionName = "init";
    QSqlDatabase db;
    if (QSqlDatabase::contains(connectionName)) {
        db = QSqlDatabase::database(connectionName);
        if (!db.isOpen()) {
            if (!db.open()) {
                qDebug() << "无法打开已存在的数据库连接saveFriendInfo:" << db.lastError().text();
                    return ;
            }
        }
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        QString databasePath = USER_PATH + "user.db";
        db.setDatabaseName(databasePath);
        if (!db.open()) {
            qDebug() << "无法打开新的数据库连接saveFriendInfo:" << db.lastError().text();
                return ;
        }
    }

    // 创建表
    QSqlQuery query(db);
    QString createTableQuery = "CREATE TABLE IF NOT EXISTS contacts ("
                               "friend_id INTEGER PRIMARY KEY, "
                               "name TEXT, "
                               "email TEXT, "
                               "avatar TEXT)";
    if (!query.exec(createTableQuery)) {
        qDebug() << "创建表时出错saveFriendInfo:" << query.lastError().text();
                                             return ;
    }

    // 遍历 QJsonArray 并插入数据
    for (const auto& jsonValue : friendList) {
        QJsonObject jsonObj = jsonValue.toObject();
        int friendId = jsonObj["Id"].toInt();
        QString name = jsonObj["Name"].toString();
        QString email = jsonObj["Email"].toString();
        QString avatar = jsonObj["Avatar"].toString();

        // 准备插入语句，将 id 改为 friend_id
        query.prepare("INSERT INTO contacts (friend_id, name, email, avatar) VALUES (:friend_id, :name, :email, :avatar)");
        query.bindValue(":friend_id", friendId);
        query.bindValue(":name", name);
        query.bindValue(":email", email);
        query.bindValue(":avatar", avatar);


        // 执行插入语句
        if (!query.exec()) {
        qDebug() << "插入数据时出错saveFriendInfo:" << query.lastError().text();
            return ;
        }
    }

    // 关闭数据库连接
    db.close();
}


